package com.xxx4biji.forkjoin;

import com.xxx4biji.forkjoin.ForkJoinCalculate;
import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class TestForkJoin {

    /**
     * ForkJoin框架
     */
    @Test
    public void test1() {
        Instant start = Instant.now();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate(0, 100000000L);
        Long sum = pool.invoke(task);
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗时时间" + Duration.between(start, end).toMillis()+"毫秒");
    }
    /**
     * java8后并行流改进
     */
    @Test
    public void test2(){
        Instant start = Instant.now();
        LongStream.rangeClosed(0,100000000000L)
                .parallel()//底层ForkJoin
                .reduce(0,Long::sum);
        Instant end = Instant.now();
        System.out.println("耗时时间" + Duration.between(start, end).toMillis()+"毫秒");
    }

}
